// ignore_for_file: prefer_typing_uninitialized_variables, avoid_print

import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'package:miaowu/app/module/message/message_list_page.dart';
import 'package:miaowu/app/module/mine/user_center/user_center_info_page.dart';
import 'package:miaowu/app/theme/theme_model.dart';
import 'package:miaowu/app/theme/tui_theme.dart';
import 'package:provider/provider.dart';

import '../../theme/commen_color.dart';
import '../world/world_main/world_main_page.dart';
import 'home_page.dart';
import 'navigation_bar_data.dart';

/// 首页
class TabBarPage extends StatefulWidget {
  final int pageIndex;

  const TabBarPage({Key? key, this.pageIndex = 0}) : super(key: key);

  @override
  State<StatefulWidget> createState() => TabBarPageState();
}

class TabBarPageState extends State<TabBarPage> {
  bool hasInit = false;
  var subscription;
  bool hasInternet = true;
  int currentIndex = 0;

  String pageName = "";

  // final PageController _controller = PageController(initialPage: 0);
  // List<Widget> pages = [const HomePage(title: ''), const FunyPage(), const MessagePage(), const MinePage()];

  List<String> titles = ['鱼塘', '喵星', '消息', '本喵'];
  List<String> tabbarItemImageNomal = [
    'assets/app/images/tabbar/tabbar_home_n.png',
    'assets/app/images/tabbar/tabbar_star_n.png',
    'assets/app/images/tabbar/tabbar_message_n.png',
    'assets/app/images/tabbar/tabbar_mine_n.png',
  ];
  List<String> tabbarItemImageSelected = [
    'assets/app/images/tabbar/tabbar_home_s.png',
    'assets/app/images/tabbar/tabbar_star_s.png',
    'assets/app/images/tabbar/tabbar_message_s.png',
    'assets/app/images/tabbar/tabbar_mine_s.png',
  ];

  @override
  initState() {
    super.initState();
    currentIndex = widget.pageIndex;
    setState(() {});
  }

  // Map<int, String> pageTitle(LocalSetting localSetting) {
  //   final String connectText = localSetting.connectStatus == ConnectStatus.connecting ? TIM_t("连接中...") : TIM_t("连接失败");
  //   return {
  //     0: localSetting.connectStatus == ConnectStatus.success ? TIM_t("消息") : connectText,
  //     1: TIM_t("通讯录"),
  //     2: TIM_t("我的"),
  //   };
  // }

  // List<NavigationBarData> bottomNavigatorList(theme) {
  //   return getBottomNavigatorList(context, theme);
  // }

  // Widget? getTitle(LocalSetting localSetting) {
  //   return Text(
  //     pageTitle(localSetting)[currentIndex]!,
  //     style: const TextStyle(color: Colors.white, fontSize: IMDemoConfig.appBarTitleFontSize),
  //   );
  // }

  @override
  Widget build(BuildContext context) {
    final TUITheme theme = Provider.of<DefaultThemeData>(context).theme;
    return Scaffold(
      backgroundColor: currentIndex == 0 ? const Color(0xFF0C183A) : theme.white,
      body: DefaultTabController(
        length: 4,
        child: Stack(
          children: [
            if (currentIndex == 0) Image.asset('assets/app/images/home/home_top_image.png'),
            if (currentIndex == 0)
              Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                      margin: const EdgeInsets.only(top: 130),
                      child: Lottie.asset('assets/app/json/cat_home.json', repeat: true))),
            Column(
              children: [
                Expanded(
                  child: IndexedStack(
                    index: currentIndex,
                    children: getWidgets(),
                  ),
                ),
                _buildBottomNavigationBarWarpper1(context)
              ],
            ),
          ],
        ),
      ),
      // bottomNavigationBar: BottomNavigationBar(
      //   items: List.generate(
      //     bottomNavigatorList(theme).length,
      //     (index) => BottomNavigationBarItem(
      //       icon: index == currentIndex
      //           ? bottomNavigatorList(theme)[index].selectedIcon
      //           : bottomNavigatorList(theme)[index].unselectedIcon,
      //       label: bottomNavigatorList(theme)[index].title,
      //     ),
      //   ),
      //   currentIndex: currentIndex,
      //   type: BottomNavigationBarType.fixed,
      //   onTap: (index) {
      //     _changePage(index, context);
      //     if (isNeedMoveToConversation) {
      //       if (index == 0 && currentIndex == 0) {
      //         conversationKey.currentState?.scrollToNextUnreadConversation();
      //       }
      //     }
      //     isNeedMoveToConversation = true;
      //     Future.delayed(const Duration(milliseconds: 300), () {
      //       isNeedMoveToConversation = false;
      //     });
      //   },
      //   selectedItemColor: theme.primaryColor,
      //   unselectedItemColor: Colors.grey,
      //   backgroundColor: theme.weakBackgroundColor,
      // ),
      // floatingActionButton: Container(
      //   width: 45,
      //   height: 45,
      //   color: Colors.amber,
      // ).onTap(() {
      //   Get.to(const ExamplePage());
      // }),
    );
  }

  //如果点击的导航页不是当前项，切换
  void _changePage(int index, BuildContext context) {
    if (index != currentIndex) {
      currentIndex = index;
      setState(() {
        if (index == 1) {
          pageName = 'concat';
        }
        if (index == 2) {
          pageName = 'userProfile';
        }
        if (index == 3) {
          // UserService.to.removeToken();
        }
      });
    }
  }

  Container _buildBottomNavigationBarWarpper1(BuildContext context) {
    double safeBottomHeight = MediaQuery.of(context).viewPadding.bottom;
    return Container(
        margin: EdgeInsets.only(left: 16, right: 16, bottom: safeBottomHeight != 0 ? (safeBottomHeight - 15) : 10),
        height: 65,
        alignment: Alignment.center,
        decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(32.5))),
        child: TabBar(
          isScrollable: false,
          labelColor: const Color(0xFF0C183A),
          labelStyle: const TextStyle(fontWeight: FontWeight.bold),
          unselectedLabelColor: Colors.black,
          unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.normal),
          indicatorSize: TabBarIndicatorSize.label,
          indicatorColor: Colors.transparent,
          dividerHeight: 0,
          tabs: titles
              .asMap()
              .entries
              .map((e) => Tab(
                    icon: Image.asset(
                        e.key == currentIndex ? tabbarItemImageSelected[e.key] : tabbarItemImageNomal[e.key],
                        width: 24),
                    text: e.value,
                  ))
              .toList(),
          onTap: (index) {
            _changePage(index, context);
          },
        ));
  }

  List<Widget> getWidgets() {
    return [
      const HomePage(title: ''),
      const WorldMainPage(),
      // Conversation(key: conversationKey, conversationController: _conversationController),
      // const Contact(),
      const MessageListPage(),
      const UserCenterInfoPage(),
      // Container(color: Colors.black),
    ];
  }

  List<NavigationBarData> getBottomNavigatorList(BuildContext context, theme) {
    final List<NavigationBarData> bottomNavigatorList = [
      NavigationBarData(
        widget: Container(color: Colors.black),
        title: ("消息"),
        selectedIcon: Stack(
          clipBehavior: Clip.none,
          children: [
            ColorFiltered(
              colorFilter: ColorFilter.mode(theme.primaryColor ?? CommonColor.primaryColor, BlendMode.srcATop),
              child: Image.asset("assets/chat_active.png", width: 24, height: 24),
            ),
          ],
        ),
        unselectedIcon: Stack(
          clipBehavior: Clip.none,
          children: [
            Image.asset("assets/chat.png", width: 24, height: 24),
          ],
        ),
      ),
      NavigationBarData(
        widget: Container(color: Colors.yellow),
        title: ("通讯录"),
        selectedIcon: Stack(
          clipBehavior: Clip.none,
          children: [
            ColorFiltered(
              colorFilter: ColorFilter.mode(theme.primaryColor ?? CommonColor.primaryColor, BlendMode.srcATop),
              child: Image.asset("assets/contact_active.png", width: 24, height: 24),
            ),
          ],
        ),
        unselectedIcon: Stack(
          clipBehavior: Clip.none,
          children: [Image.asset("assets/contact.png", width: 24, height: 24)],
        ),
      ),
      NavigationBarData(
        widget: Container(color: Colors.red),
        title: ("我的"),
        selectedIcon: ColorFiltered(
            colorFilter: ColorFilter.mode(theme.primaryColor ?? CommonColor.primaryColor, BlendMode.srcATop),
            child: Image.asset("assets/profile_active.png", width: 24, height: 24)),
        unselectedIcon: Image.asset("assets/profile.png", width: 24, height: 24),
      ),
    ];

    return bottomNavigatorList;
  }

  @override
  dispose() {
    super.dispose();
  }
}
